
/************************************************************/
//文件名：main.c
//功能:测试linux下iic读写SHT30
//使用说明: (1)
//          (2)
//          (3)
//          (4)
//作者:彭文正
//日期:2020-09-03

/************************************************************/
//包含头文件
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/ioctl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/select.h>
#include<sys/time.h>
#include<errno.h>
//宏定义


#define SHT30_Address                               0x44         //10001000
#define I2C_RETRIES                                 0x0701
#define I2C_TIMEOUT                                 0x0702
#define I2C_SLAVE                                   0x0703       //IIC从器件的地址设置
#define I2C_BUS_MODE                                0x0780

typedef unsigned char uint8;
int fd = -1;

//函数声明
static uint8 SHT30_Init(void);


//
static uint8 SHT30_Init(void)
{
    fd  = open("/dev/i2c-0", O_RDWR);               // open file and enable read and  write

    if (fd < 0)
    {
        perror("Can't open /dev/SHT30 \n");       // open i2c dev file fail
        exit(1);
    }

    printf("open /dev/i2c-0 success !\n");          // open i2c dev file succes

    if (ioctl(fd, I2C_SLAVE,SHT30_Address) < 0)
    { //set i2c address
        printf("fail to set i2c device slave address!\n");
        close(fd);
        return - 1;
    }

    printf("set slave address to 0x%x success!\n", SHT30_Address);
   
    return (1);
}

// main
int main(int argc, char * argv[])
{
    unsigned char buf[8] = {0};
    SHT30_Init();
    usleep(1000 * 100);
    float temperature=0;
    float humidity=0;
    while (1)
    {
    buf[0] = 0x2C;
    buf[1] = 0x0D;
    if ( write(fd, buf, 2) != 2 ) {
        perror("faile to write config.\n");
        return -1;
    }
    buf[0] = 0;
    buf[1] = 0;
    if (read(fd, buf, 6) != 6 ) {
        perror("faile to read back configure data.\n");
        return -1;
    }    
    printf("SHT30---->: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x \n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5] );
    temperature = ((float)((buf[0]<<8)+buf[1]))*175/65535-45;
    humidity = ((float)((buf[3]<<8)+buf[4]))*100/65535;
    printf("temperature:%f   humidity:%f\r\n",temperature,humidity);
    usleep(1000 * 200);
    }
    close(fd);
}
